import java.util.Comparator;
import java.util.TreeMap;

public class Solution1438 {
    public int longestSubarray(int[] nums, int limit) {
        int l=0;
        TreeMap<Integer,Integer> treeMap=new TreeMap<>(Comparator.comparingInt(a -> a));
        treeMap.put(nums[0],1);
        int ans=1;
        for (int r=1;r<nums.length;r++){
            while (!treeMap.isEmpty()){
                int rr=treeMap.lastKey();
                int ll=treeMap.firstKey();
                if (Math.abs(nums[r]-rr)<=limit && Math.abs(nums[r]-ll)<=limit){
                    break;
                }
                treeMap.put(nums[l],treeMap.get(nums[l])-1);
                if (treeMap.get(nums[l])==0){
                    treeMap.remove(nums[l]);
                }
                l++;
            }
            treeMap.put(nums[r],treeMap.getOrDefault(nums[r],0)+1);
            ans=Math.max(ans,r-l+1);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1438().longestSubarray(new int[]{4,2,2,2,4,4,2,2},0));
    }
}
